package statement;

import bean.User;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.Scanner;

public class StatementTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String user = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();

        String sql = "SELECT id, name, password, address, phone FROM user WHERE name='" + user +  "' AND password='" + password +"'";

        System.out.println(sql);

        User person = null;
        person = getInstance(sql, User.class);
        System.out.println(person);
    }

    /**
     * 执行 SQL 语言，返回 查询对象
     * @param sql 要执行的 SQL 语句
     * @param className 返回对象的类型
     * @return
     */
    public static <T> T getInstance(String sql , Class<T> className){
        T t = null;

        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/java_jdbc?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String user= "root";
        String password = "it";

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 创建数据库连接
            connection = DriverManager.getConnection(url, user, password);
            // 通过数据库连接创建 Statement 对象
            statement = connection.createStatement();
            // 执行数据库查询，将查询结果保存到返回值
            resultSet = statement.executeQuery(sql);

            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            System.out.println(columnCount);

            if (resultSet.next()){
                // 使用反射形式创建对象并赋值
                t = className.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    // 获取 列的名称
                    String columnName = metaData.getColumnName(i + 1);
                    // System.out.println(columnName);
                    // 获取列的别名
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    // System.out.println(columnLabel);

                    Object object = resultSet.getObject(columnName);
//                    System.out.println(object);


                    Field field = className.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, object);
                }
            }

            statement.close();
            connection.close();
        } catch (SQLException | IllegalAccessException | InstantiationException | NoSuchFieldException throwables) {
            throwables.printStackTrace();
        } finally {


        }

        return t;
    }
}
